<?php

namespace app\manage\controller;

use app\model\Role;
use app\model\Admin;
use app\model\Mch;
use think\Db;

class System extends Base
{
    /**
     * Undocumented 角色列表
     *
     * @param Request $request
     * @return void
     */
    public function role(){

        $this->assign("role",Role::select());
        
        return view("role");
    }
    /**
     * Undocumented 编辑权限
     *
     * @param Request $request
     * @return void
     */
    public function role_details(){
        if($this->request->isAjax()){
            $data = $this->request->param('action');
            $result = Role::where("id",$this->request->param("role_id"))->update(['action'=>$data]);
            if($result){
                get_list_insert('role',Role::select());
                $redis = new \Predis\Client();
                $redis->set('menu',json_encode(Db::name("menu")->select()));//
                $this->success('操作成功','/manage/role');
            }else{
                $this->error("操作失败");
            } 
        }
        $role_id = $this->request->param("id");
        $info = Role::where("id",$role_id)->find();
        $data['id'] =$info->id;
        $data['action'] = explode(",",$info->action);
        $this->assign("data",$data);
        if($role_id == '6' || $role_id == '7'){
            $this->assign("list",getTree(Db::name("menu")->where('status',2)->select()));
        }else{
            $this->assign("list",getTree(Db::name("menu")->where('status',1)->select()));
        }
        
        return view("update_role");
    }
    /**
     * Undocumented 菜单
     *
     * @return void
     */
    public function menu(){

        $menu = Db::name("menu")->where('status',1)->select();
        $list = $this->getMenu($menu);
        $this->assign("list",$list);
        $this->assign("mch_list",$this->getMenu(Db::name("menu")->where('status',2)->select()));
        $this->assign("tree",make_option_tree_for_select($menu));
        $this->assign("mch_tree",make_option_tree_for_select($this->getMenu(Db::name("menu")->where('status',2)->select())));
        return view("menu");
    }
    /**
     * Undocumented 编辑菜单
     *
     * @return void
     */
    public function menuEdit(){
        if($this->request->isPost()){
            $data = $this->request->param();
            unset($data['admin_auth']);
            unset($data['pid']);
            $id = $data['id'];
            unset($data['id']);
            $result = Db::name("menu")->where("id",$id)->update(array_filter($data));
            if(!$result){
                return $this->success('修改失败');
            }
            return $this->success('修改成功');
        }
        $info = Db::name("menu")->where("id",$this->request->param('id'))->find();
        if(empty($info)){
            return $this->error("数据不存在");
        }
        if($info['status'] == 1){//后台菜单
            $this->assign("menutree",make_option_tree_for_select($this->getMenu(Db::name("menu")->where('status',1)->select()),0,$info['id']));
        }else{//商户菜单
            $this->assign("menutree",make_option_tree_for_select($this->getMenu(Db::name("menu")->where('status',2)->select()),0,$info['id']));
        }
        $this->assign("info",$info);
        return view("menuEdit");
    } 
    public function addMenu(){
        $data = $this->request->param();
      
        unset($data['admin_auth']);
        Db::startTrans();
        try {
            Db::name("menu")->insert(array_filter($data));
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        $client = new \Predis\Client();
        $client->set("menu",json_encode(Db::name("menu")->select()));
        return $this->success("添加成功");
    }
    /**
     * Undocumented 菜单排序
     *
     * @return void
     */
    public function menuSort(){
      
        $info = Db::name("menu")->where("id",$this->request->param('id'))->find();
        if(!$info){
            return $this->error("数据不存在");
        }
        Db::startTrans();
        try {
            Db::name("menu")->where("id",$info['id'])->update(array("sort"=>$this->request->param('sort')));
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        $client = new \Predis\Client();
        $client->set("menu",json_encode(Db::name("menu")->select()));
        $this->success('操作成功');
    }
    /**
     * Undocumented 菜单状态
     *
     * @return void
     */
    public function menuType(){
        $id = $this->request->param('mid');
        $info = Db::name("menu")->where("id",$id)->find();
        if(!$info){
            return $this->error("数据不存在");
        }
        $type = $info['type']==2 ? '1' : '2';
        Db::startTrans();
        try {
            Db::name("menu")->where("id",$info['id'])->update(array("type"=>$type));
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        $client = new \Predis\Client();
        $client->set("menu",json_encode(Db::name("menu")->select()));
        $this->success('操作成功');
    }
    /**
     * Undocumented 删除菜单
     *
     * @return void
     */
    public function meunDel(){
        $id = $this->request->param('id');
        $info = Db::name("menu")->where("id",$id)->find();
        if(!$info){
            return $this->error("数据不存在");
        }
        if(Db::name("menu")->where("pid",$id)->find()){
            return $this->error("请先删除下级");
        }
        Db::startTrans();
        try {
            Db::name("menu")->where("id",$info['id'])->delete();
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        $client = new \Predis\Client();
        $client->set("menu",json_encode(Db::name("menu")->select()));
        return $this->success('操作成功');
    }
    /**
     * Undocumented 后台管理账号
     *
     * @return void
     */
    public function system_account(){
        
        $this->assign("list",Admin::field("id,user_name,nickname,role_id,type,create_time")->select());
        $this->assign("role",Role::field("id,role_name")->select());
        return view('account');
    }
    /**
     * Undocumented 修改密码
     *
     * @return void
     */
    public function up_pwd(){
        $old_pwd = $this->request->param("old_pwd",'','strip_tags,trim');
        $new_pwd = $this->request->param("new_pwd",'','strip_tags,trim');
        $pwd = $this->request->param("pwd",'','strip_tags,trim');
        if($new_pwd == $old_pwd){
            return $this->error("新密码不能和旧密码相同");
        }
        if($new_pwd != $pwd){
            return $this->error("确认密码和新密码不一致");
        }
        $admin_auth = Session("auth_admin");
        if(!$admin_auth){
            return $this->error("登录超时",'/manage/login');
        }
        $info = Admin::where("id",$admin_auth['auth_admin_id'])->find();
        $Aes = new \Aes();
        $o_pwd = $Aes->decrypt($info->password);//解密
        if($o_pwd != $old_pwd){
            return $this->error("旧密码输入错误");
        }
        $info->password = $Aes->encrypt($new_pwd);
        $info->save();
        return $this->success("修改成功");
    }
    /**
     * Undocumented 获取角色列表
     *
     * @return void
     */
    public function ajax_select(){
        $info = array();
        $id = $this->request->param('id');
        if(empty($id)){
            $select = Role::selectRole();
        }else{
            $info = Admin::where("id",$id)->field("id,user_name,role_id,nickname")->find();
            $select = Role::selectRole($info->role_id);
        }
        return [ 'info'=>$info,'select'=>$select ];
    }
    /**
     * Undocumented 网站维护：开启/关闭
     *
     * @return void
     */
    public function maintain(){
        $redis = new \Predis\Client();
        $status = $redis->get('web');
        if(empty($status)){
            $redis->set('web',1);
            $status = 1;
        }
        $type = $status ==1 ? 2 : 1;
        $redis->set('web',$type);
        $this->success('操作成功');
    }
    /**
     * Undocumented 添加/编辑账号
     *
     * @return void
     */
    public function save_account(){
        
        $data = $this->request->param();
        if(empty($data['name']) && empty($data['pwd']) && empty($data['pid'])){
            return $this->error("缺少必填项");
        }
        $result = Admin::adminAdd($data);
        if($result === true){
            if(!empty($data['role_id'])){//更新
                if($data['pid'] == 2){
                    getLog($this->request->admin_auth['auth_admin_id'],$this->request->admin_auth['role_id'],'更新代理商账号ID['.$data['role_id'].']信息');
                }else{
                    getLog($this->request->admin_auth['auth_admin_id'],$this->request->admin_auth['role_id'],'更新其他角色账号ID['.$data['role_id'].']信息');
                }
            }else{
                if($data['pid'] == 2){
                    $txt = '创建其他类型账号：['.$data['name'].']';
                }elseif($data['pid'] == 3){
                    $txt = '创建运营账号：['.$data['name'].']';
                }
                elseif($data['pid'] == 4){
                    $txt = '创建客服账号：['.$data['name'].']';
                }
                elseif($data['pid'] == 5){
                    $txt = '创建财务账号：['.$data['name'].']';
                }else{
                    $txt = '创建超级管理员账号：['.$data['name'].']';
                }
                getLog($this->request->admin_auth['auth_admin_id'],$this->request->admin_auth['role_id'],$txt);
            }
            
            return $this->success("操作成功");
        }else{
            return $this->error($result);
        }
    }
    /**
     * Undocumented 更新账号状态
     *
     * @return void
     */
    public function account_status(){
        $id = $this->request->param("mid");
        $info = Admin::where("id",$id)->find();
        if(empty($info)){
            return $this->error("数据不存在");
        }
        $info->type = $info->type == 2 ? 1 : 2;
        $info->save();
        $st = $info->type == 1 ? '开启' : '禁用';
        if($info->role_id == 3){
            $txt = '更新运营['.$info->nickname.']状态为：'.$st;
        }
        elseif($info->role_id == 4){
            $txt = '更新客服['.$info->nickname.']状态为：'.$st;
        }
        elseif($info->role_id == 5){
            $txt = '更新财务['.$info->nickname.']状态为：'.$st;
        }else{
            $txt = '更新超级管理员['.$info->nickname.']状态为：'.$st;
        }
        getLog($this->request->admin_auth['auth_admin_id'],$this->request->admin_auth['role_id'],$txt);
        return $this->success("操作成功");
    }
    /**
     * Undocumented 删除账号
     *
     * @return void
     */
    public function acc_delete(){
        $id = $this->request->param("id");
        $info = Admin::where("id",$id)->find();
        if(!empty($info)){
            $info->delete();
            return $this->success("操作成功");
        }
        return $this->error("数据不存在");
    }
    /**
     * Undocumented 操作记录
     *
     * @return void
     */
    public function log(){
        $list = Db::name("log")->order("id",'desc')->where(function($query){
            $start = input("start",date('Y-m-d 00:00:00',time()));
            $end = input("end",date('Y-m-d H:i:s',time()));
            if(!empty($start) && !empty($end)){
                $query->where("create_time",'between',[$start,$end]);
            }
        })->paginate(10,false,['query' =>$this->request->param()]);
        $page = $list->render();
        $this->assign("data",$this->request->param());
        $this->assign("list",$list);
        $this->assign("page",$page);
       return view('log'); 
    }
    /**
     * Undocumented IP黑名单
     *
     * @return void
     */
    public function black_list(){
        $list= Db::name("white_ip")->order('id','desc')->where(function($query){
            $ip = input('ip');
            if(!empty($ip)){
                $query->where('white_ip',$ip);
            }
        })->paginate(10);
        $page = $list->render();
        $this->assign("list",$list);
        $this->assign("data",$this->request->param());
        $this->assign("page",$page);
        return view("location/black_ip_list");
    }
    /**
     * Undocumented 添加/删除黑名单
     *
     * @return void
     */
    public function blacklistSave(){
        $type = $this->request->param("type",'','strip_tags,trim');
        if($type == 1){//添加
            $remark = $this->request->param("remark",'','strip_tags,trim');
            $white_ip = $this->request->param("white_ip",'','strip_tags,trim');
            Db::name("white_ip")->insert(array(
                "white_ip" => $white_ip,
                "remark"   => $remark
            ));
        }else{//删除
            $pid = $this->request->param("pid",'','strip_tags,trim');
            Db::name("white_ip")->where("id",$pid)->delete();
        }
        return $this->success('操作成功');
    }
    /**
     * Undocumented 商户下单
     *
     * @return void
     */
    public function with_blacklist(){
        $list= Db::name("mch_white_ip")->order('id','desc')->where(function($query){
            $keyword = input("keyword");
            if(!empty($keyword)){
                $mch = Mch::where("mch|mch_name",'like','%'.$keyword.'%')->column("mch");
                if($mch){
                    $query->where("mch_id",'in',$mch);
                }
            }
        })->paginate(10,false,['query' =>$this->request->param()]);
        $mch = get_list_k('mch');
        if(!$mch){
            $mch = Mch::where("is_agent",'1')->field("mch,is_agent,mch_name")->select();
        }
        $page = $list->render();
        $this->assign("data",$this->request->param());
        $this->assign("mch",$mch);
        $this->assign("list",$list);
        $this->assign("page",$page);
        return view("location/mch_black_list");
    }
    /**
     * Undocumented 添加/编辑/删除商户下单白名单
     *
     * @return void
     */
    public function mch_ip_save(){
       
        $type = $this->request->param("type",'','strip_tags,trim');
        if($type == 1){//添加
            $remark = $this->request->param("remark",'','strip_tags,trim');
            $mch = $this->request->param("mch_id",'','strip_tags,trim');
            $white_ip = $this->request->param("white_ip",'','strip_tags,trim');
            if(!empty($this->request->param('w_id'))){//编辑
                Db::name("mch_white_ip")->where("id",$this->request->param('w_id'))->update(array(
                    "white_ip" => $white_ip,
                    "mch_id" => $mch,
                    "remark"   => $remark
                ));
            }else{//添加
                Db::name("mch_white_ip")->insert(array(
                    "white_ip" => $white_ip,
                    "mch_id" => $mch,
                    "remark"   => $remark
                ));
            }
        }else{//删除
            $pid = $this->request->param("pid",'','strip_tags,trim');
            Db::name("mch_white_ip")->where("id",$pid)->delete();
        }
        return $this->success('操作成功');
    }
    /**
     * Undocumented 商户提现
     *
     * @return void
     */
    public function withdrawal_ip(){
        $list= Db::name("mch_withdrawal_ip")->order('id','desc')->where(function($query){
            $keyword = input("keyword");
            if(!empty($keyword)){
                $mch = Mch::where("mch|mch_name",'like','%'.$keyword.'%')->column("mch");
                if($mch){
                    $query->where("mch_id",'in',$mch);
                }
            }
        })->paginate(10,false,['query' =>$this->request->param()]);;
        $mch = get_list_k('mch');
        if(!$mch){
            $mch = Mch::where("is_agent",'1')->field("mch,is_agent,mch_name")->select();
        }
        $page = $list->render();
        $this->assign("mch",$mch);
        $this->assign("data",$this->request->param());
        $this->assign("list",$list);
        $this->assign("page",$page);
        return view("location/mch_withdrawal_ip");
    }
    /**
     * Undocumented 商户日志
     *
     * @return void
     */
    public function mchLog(){
        $list = Db::name("mch_log")->order("id",'desc')->where(function($query){
            $start = input("start",date('Y-m-d 00:00:00',time()));
            $end = input("end",date('Y-m-d H:i:s',time()));
            if(!empty($start) && !empty($end)){
                $query->where("create_time",'between',[$start,$end]);
            }
        })->paginate(10,false,['query' =>$this->request->param()]);
        $page = $list->render();
        $this->assign("data",$this->request->param());
        $this->assign("list",$list);
        $this->assign("page",$page);
        return view("mch_log");
    }
    /**
     * Undocumented 编辑
     *
     * @return void
     */
    function mch_ip_edit(){

        $id = $this->request->param('mid');
        $info = Db::name("mch_white_ip")->where('id',$id)->find();
        if(!$info){
            return $this->error("数据不存在");
        } 
        $mch = get_list_k('mch');
        if(!$mch){
            $mch = Mch::where("is_agent",'1')->field("mch,mch_name")->select();
        }
        $this->assign("info",$info);
        $this->assign("mch",$mch);
        return view("location/mch_ip_edit"); 
    }
     /**
     * Undocumented 编辑
     *
     * @return void
     */
    function with_ip_edit(){
        $id = $this->request->param('mid');
        $info = Db::name("mch_withdrawal_ip")->where('id',$id)->find();
        if(!$info){
            return $this->error("数据不存在");
        } 
        $mch = get_list_k('mch');
        if(!$mch){
            $mch = Mch::where("is_agent",'1')->field("mch,mch_name")->select();
        }
        $this->assign("info",$info);
        $this->assign("mch",$mch);
        return view("location/edit_with_ip"); 
    }
    /**
     * Undocumented 添加/删除商户提现白名单
     *
     * @return void
     */
    public function withdrawal_ip_save(){
       
        $type = $this->request->param("type",'','strip_tags,trim');
        if($type == 1){//添加
            $remark = $this->request->param("remark",'','strip_tags,trim');
            $white_ip = $this->request->param("white_ip",'','strip_tags,trim');
            $mch = $this->request->param("mch_id",'','strip_tags,trim');
            if(!empty($this->request->param("w_id"))){
                Db::name("mch_withdrawal_ip")->where("id",$this->request->param("w_id"))->update(array(
                    "white_ip" => $white_ip,
                    "mch_id" => $mch,
                    "remark"   => $remark
                ));
            }else{
                Db::name("mch_withdrawal_ip")->insert(array(
                    "white_ip" => $white_ip,
                    "mch_id" => $mch,
                    "remark"   => $remark
                ));
            }
        }else{//删除
            $pid = $this->request->param("pid",'','strip_tags,trim');
            Db::name("mch_withdrawal_ip")->where("id",$pid)->delete();
        }
        return $this->success('操作成功');
    }
}